package com.mskj.zxmy.service.serviceImpl;

import cn.dev33.satoken.stp.StpUtil;
import com.mskj.zxmy.common.BusinessException;
import com.mskj.zxmy.dto.SignDTO;
import com.mskj.zxmy.entity.ProcessSigningTable;
import com.mskj.zxmy.mapper.AttendanceMapper;
import com.mskj.zxmy.service.AttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;

@Service
public class AttendanceServiceImpl implements AttendanceService {

    @Autowired
    private AttendanceMapper attendanceMapper;

    @Override
    public void signIn(SignDTO dto) {
        String user = StpUtil.getLoginId().toString();
        String processName = dto.getProcessName();
        LocalDate today = LocalDate.now();
        LocalDateTime now = LocalDateTime.now();

        // 1. 查询该用户当天所有未签出的记录（不限定工序）
        List<ProcessSigningTable> unSignedOutRecords = attendanceMapper.findTodayAllUnsignOutByUser(user, today);

        // 2. 自动签出所有未完成的记录（用当前签到时间作为它们的签出时间）
        if (unSignedOutRecords != null && !unSignedOutRecords.isEmpty()) {

            for (ProcessSigningTable record : unSignedOutRecords) {
                attendanceMapper.updateSignOutTimeAndStatus(
                        record.getId(),
                        now,
                        "签出"

                );
                removeUserFromProcessBasicTable(record.getProcessName(), user);
            }


        }

        // 3. 插入新工序的签到记录
        ProcessSigningTable entity = new ProcessSigningTable();
        entity.setSignTime(now);
        entity.setProcessName(processName);
        entity.setSignatureDate(today);
        entity.setSignIn(user);
        entity.setSignStatus("签到");
        attendanceMapper.insertSignIn(entity);
        String users = attendanceMapper.getprocessBasicTablesUser(dto.getProcessName());
        boolean userExists = false;
        if (users != null && !users.isEmpty()) {
            userExists = Arrays.stream(users.split(","))
                    .map(String::trim)
                    .anyMatch(u -> u.equals(user));
        }

        if (userExists) {
            // 用户已存在，执行相应逻辑
            throw new BusinessException("当前用户已在签到列表中");
        } else {
            // 用户不存在，可以添加用户
            String updatedUsers = (users == null || users.isEmpty()) ? user : users + "," + user;
            attendanceMapper.updateProcessBasicTables(dto.getProcessName(), updatedUsers);
        }
        // 4. 同步基础表签到人（去重逻辑）
        syncProcessSignIn(processName, user);
    }

    @Override
    public void signOut(SignDTO dto) {
        String user = StpUtil.getLoginId().toString();
        String processName = dto.getProcessName();
        LocalDate today = LocalDate.now();

        // 查询该用户当天在工序的未签出记录
        ProcessSigningTable record = attendanceMapper.selectByUserProcessAndDate(user, today);

        if (record == null) {
            throw new BusinessException("请先签到【" + processName + "】工序！");
        }
        if ("签出".equals(record.getSignStatus())) {
            throw new BusinessException("【" + processName + "】工序已签出，无需重复操作！");
        }
        //如果dto的ProcessName不等于record.getProcessName就返回报错，当前签出工序错误
        if (!dto.getProcessName().equals(record.getProcessName())) {
            throw new BusinessException("当前签出工序错误！");
        }
        // 正常签出当前工序
        attendanceMapper.updateSignOutTimeAndStatusByProcessName(record.getProcessName(), LocalDateTime.now(), "签出");
        // 从基础表中移除签到人
        removeUserFromProcessBasicTable(processName, user);
    }

    /**
     * 根据工序id查询工序名称
     *
     * @param processId
     * @return
     */
    @Override
    public String getProcessNameByProcessId(Integer processId) {
        return attendanceMapper.getProcessNameByProcessId(processId);

    }

    /**
     * 从工序基础表中移除指定用户
     */
    private void removeUserFromProcessBasicTable(String processName, String userToRemove) {
        // 获取当前工序基础表中的用户列表
        String currentUsers = attendanceMapper.getProcessSignIn(processName);

        if (currentUsers != null && !currentUsers.isEmpty()) {
            // 将用户列表分割成数组
            List<String> userList = new ArrayList<>(Arrays.asList(currentUsers.split(",")));

            // 移除指定用户
            userList.removeIf(user -> user.trim().equals(userToRemove));

            // 重新构建用户列表字符串
            String updatedUsers = String.join(",", userList);

            // 更新数据库中的用户列表
            attendanceMapper.updateProcessBasicTables(processName, updatedUsers);
        }
    }

    /**
     * 同步基础表签到人（去重逻辑）
     */
    private void syncProcessSignIn(String processName, String user) {
        String dbSignInList = attendanceMapper.getProcessSignIn(processName);
        List<String> signInList = dbSignInList == null ? new ArrayList<>() : Arrays.asList(dbSignInList.split(","));

        if (!signInList.contains(user)) {
            attendanceMapper.updateProcessSignIn(processName, user);
        }
    }
}